<template>
  <div class="dailyTask" v-title data-title="日常任务单新增页面">
    <home-nav :userData="userinfo"></home-nav>    
    <div class="navigator">
      <div class="baseinfo">        
        <div style="display: flex;">
          <span style="margin: 0px auto 30px auto;font-weight: bold;font-size: 20px;">新增任务单</span>
          <span style="color: #31a0e1" v-show="id" @click="openHistory">操作日志</span>
        </div>
        <a-form-model class="hte-form-model" ref="ruleForm" :model="form" :rules="rules">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item
                label="任务单编号"
                prop="taskNo"
              >
                <a-input v-model="form.taskNo" disabled placeholder='系统自动生成'/>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="任务单分类"
                prop="taskTypeName"
              >
                <a-input v-model="form.taskTypeName" disabled/>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="taskName"
                label="任务单名称"
                prop="taskName"
              >
                <a-input
                  v-model="form.taskName"
                  @blur="
                    () => {
                      $refs.taskName.onFieldBlur()
                    }
                  "
                  placeholder="请输入任务单名称"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item
                :label="form.taskType == 'hrManage' ? '统筹人':'创建人'"
                prop="createUserName"
              >
                <a-input v-model="form.createUserName" disabled/>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="创建时间"
                prop="createDate"
              >
                <a-input :value="form.createDate ? timeFormat(form.createDate):nowDate" disabled/>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="主导团队"
                prop="mainDeptName"
              >
                <a-input v-model="form.mainDeptName" disabled/>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24" v-if="form.taskType != '30'">
            <a-col :span="8">
              <a-tooltip>
                <template slot="title">
                  个人类型是指子任务执行人员都是自己，团队类型可以选择其他人员
                </template>
                <a-form-model-item
                  ref="taskBuildType"
                  label="任务单类型"
                  prop="taskBuildType"
                >
                  <a-radio-group v-model="form.taskBuildType" :disabled="kpi.data.length > 0 || form.taskType == 'hrManage'">
                    <a-radio value="1">个人</a-radio>
                    <a-radio value="2">团队</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-tooltip>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="startDate"
                label="任务开始时间"
                prop="startDate"
              >
              <!-- :disabled-date="disabledDate"  -->
                <a-date-picker v-model="form.startDate" placeholder="请输入任务开始时间" :allowClear="false"  :disabled-date="disabledDate"
                    @change="((date,dateString)=>{dateSelect(date,dateString,1)})"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="endDate"
                label="计划完成时间"
                prop="endDate"
              >
                <a-date-picker v-model="form.endDate" placeholder="任务计划完成时间" :allowClear="false" :disabled-date="disabledEndDate" 
                  @change="((date,dateString)=>{dateSelect(date,dateString,2)})"/>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '30'">
            <a-col :span="8">
              <a-tooltip>
                <template slot="title">
                  个人类型是指子任务执行人员都是自己，团队类型可以选择其他人员
                </template>
                  <a-form-model-item
                    ref="taskBuildType"
                    label="任务单类型"
                    prop="taskBuildType"
                  >
                    <a-radio-group v-model="form.taskBuildType" :disabled="kpi.data.length > 0">
                      <a-radio value="1">个人</a-radio>
                      <a-radio value="2">团队</a-radio>
                    </a-radio-group>
                  </a-form-model-item>
              </a-tooltip>    
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="productSystem"
                label="产品系统"
                prop="productSystem"
              >
                <a-cascader
                  v-model="casModel"
                  :options="casProductSystemOptions"
                  :load-data="casLoadData"
                  placeholder="请选择产品系统"
                  change-on-select
                  @change="casProductSystemOnChange"
                  class="headcas"
                />  
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="handlerName"
                label="迭代负责人"
                prop="handlerName"
              >
                <a-select
                  show-search
                  :value="form.handlerName"
                  placeholder="输入账号或者名称查找用户"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchHandleUser"
                  @change="fetchHandleChange"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userHandleData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '30'">
            <a-col :span="8">
              <a-form-model-item
                ref="startDate"
                label="任务开始时间"
                prop="startDate"
              >
              <!-- :disabled-date="disabledDate"  -->
                <a-date-picker v-model="form.startDate" placeholder="请输入任务开始时间" :allowClear="false" :disabled-date="disabledDate" 
                    @change="((date,dateString)=>{dateSelect(date,dateString,1)})"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="endDate"
                label="计划完成时间"
                prop="endDate"
              >
                <a-date-picker v-model="form.endDate" placeholder="任务计划完成时间" :allowClear="false" :disabled-date="disabledEndDate" 
                  @change="((date,dateString)=>{dateSelect(date,dateString,2)})"/>
                  <!-- :disabled="kpi.data.length > 0" -->
              </a-form-model-item>
            </a-col>

            <a-col :span="8" >
              <a-form-model-item
                ref="versionNo"
                label="版本号"
                prop="versionNo"
              >
                <a-input v-model="form.versionNo"  placeholder='格式：v1.0.0 || V1.0.0 ' @blur="
                    () => {
                      $refs.versionNo.onFieldBlur()
                    }
                  "/>
              </a-form-model-item>
              <span style="color:red" v-show="versionTip">当前版本号前5(参考)： {{versionTip}}</span>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '30' && form.id">
            <a-col :span="24">
              <a-form-model-item
                ref="hasSendNotice"
                label="是否已上线"
                prop="hasSendNotice"
              > 
                <a-tooltip>
                  <template slot="title">
                    <span>是否已上线是指【整个任务单的完成状态是以该字段为准，即使所有子任务已完成】<br>当所有子任务和缺陷都完成时，任务单创建人或迭代负责人可修改该状态。</span>
                  </template>
                    <a-radio-group v-model="form.hasSendNotice" :disabled="!(form.status == 2 && (currentUserId == form.createUserId || currentUserId == form.handlerId))">
                      <a-radio value="1">未完成</a-radio>
                      <a-radio value="2">已完成并且已发通知</a-radio>
                      <a-radio value="3">已完成但无需发通知</a-radio>
                    </a-radio-group>
                </a-tooltip>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '11'">
            <a-col :span="8">
              <a-form-model-item
                ref="doctorName"
                label="博士后姓名"
                prop="doctorName"
              >
                <a-select
                  show-search
                  :value="form.doctorName"
                  placeholder="输入账号或者名称查找用户"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchDoctorUser"
                  @change="fetchDoctorChange"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userDoctorData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="workDeptName"
                label="工作部门/经营体"
                prop="workDeptName"
              >
                <a-select
                   show-search
                  :value="form.workDeptName"
                  placeholder="输入组织架构名称查找"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchWorkDept"
                  @change="workDeptChange"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in workDeptData" :key="index" :value="d.deptId">
                    {{ d.deptName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="teacherName"
                label="工作站导师"
                prop="teacherName"
              >
                <a-select
                  show-search
                  :value="form.teacherName"
                  placeholder="输入账号或者名称查找用户"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchTeacherUser"
                  @change="fetchTeacherChange"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userTeacherData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '11'">
            <a-col :span="24">
              <a-form-model-item
                ref="reseachTopic"
                label="研究项目课题:"
                prop="reseachTopic"
              >
                <a-textarea
                  v-model="form.reseachTopic"
                  @blur="
                    () => {
                      $refs.reseachTopic.onFieldBlur()
                    }
                  "
                  :auto-size="{ minRows: 1, maxRows: 6 }"
                  placeholder="输入课题名称，500字以内" :maxLength="500" 
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '11'">
            <a-col :span="24">
              <a-form-model-item
                ref="station"
                label="流动站名称:"
                prop="station"
              >
                <a-textarea
                  v-model="form.station"
                  @blur="
                    () => {
                      $refs.station.onFieldBlur()
                    }
                  "
                  :auto-size="{ minRows: 1, maxRows: 6 }"
                  placeholder="手动输入学校及二级学院名称，500字以内" :maxLength="500" 
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '11'">
            <a-col :span="8">
              <a-form-model-item
                ref="stationTeacher"
                label="流动站导师"
                prop="stationTeacher"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 15 }"
              >
                <a-input
                  v-model="form.stationTeacher"
                  placeholder="手动输入姓名"
                  @blur="
                    () => {
                      $refs.stationTeacher.onFieldBlur()
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="amount"
                label="联合培养费"
                prop="amount"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 15 }"
              >
                <a-input
                  v-model="form.amount"
                  @blur="
                    () => {
                      $refs.amount.onFieldBlur()
                    }
                  "
                  placeholder="请输入联合培养费"
                  type="number"
                >
                <span slot="addonAfter">万元/年</span>
                </a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == 'hrManage'">
            <a-col :span="8">
              <a-form-model-item
                ref="manageType"
                label="来源"
                prop="manageType"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 15 }"
              >
                <a-input
                  v-model="form.manageType"
                  @blur="
                    () => {
                      $refs.manageType.onFieldBlur()
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="manageError"
                label="异常点"
                prop="manageError"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 15 }"
              >
                <a-input
                  v-model="form.manageError"
                  @blur="
                    () => {
                      $refs.manageError.onFieldBlur()
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                ref="managePoint"
                label="问题焦点"
                prop="managePoint"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 15 }"
              >
                <a-input
                  v-model="form.managePoint"
                  @blur="
                    () => {
                      $refs.managePoint.onFieldBlur()
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" v-if="form.taskType == '12'">
            <a-col :span="8">
              <a-form-model-item
                ref="rewardYear"
                label="奖励期号"
                prop="rewardYear"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 15 }"
              >
                <a-select v-model="form.rewardYear" style="width: 50%">
                  <a-select-option :value="item.code" v-for="item in yearList" :key="item.code"> {{item.label}} </a-select-option>
                </a-select>
                <a-select v-model="form.rewardQuarter" style="width: 50%">
                  <a-select-option :value="item.code" v-for="item in quarterList" :key="item.code"> {{item.label}} </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item
                ref="outOpenRangeName"
                label="开放范围"
                prop="outOpenRangeName"
              >
                <a-select
                  v-model="outOpenRangeName"
                  mode="multiple"
                  placeholder="输入账号或者名称查找用户"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchOpenUser"
                  @change="handleOpenChange"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userOpenData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item
                ref="target"
                label="任务完成目标:"
                prop="target"
              >
                <a-textarea
                  v-model="form.target"
                  @blur="
                    () => {
                      $refs.target.onFieldBlur()
                    }
                  "
                  :auto-size="{ minRows: 3, maxRows: 6 }"
                  placeholder="500字以内" :maxLength="500" 
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-divider style="margin: 20px 0;" />

          <div class="info-title">相关附件
            <ht-upload
              v-show="showEditBtn"
              ref="myUpload"
              class="upload-demo"
              multiple
              dbKey="Trd"
              busField="workTask"
              busType="workTask"
              :busKey="id"
              ftpKey="ftp"
              v-model="fileList"
              :show-file-list="false"
            >
              <a-button type="primary"><a-icon type="plus" />新增附件</a-button>
            </ht-upload>
              <span>
                <img src="@/assets/attention-red.png" alt="" style="width:12px;margin: 0px 5px 0px 5px;"/>
                <span style="font-size: 14px;">附件非必填，如有相关附件可以上传，例如收益计算明细，计算方法，该任务单的方案、规划、工作要求等。</span>
              </span>
          </div>          
          <div style="margin-top:10px;">
            <a-table
              class="hte-table-content"
              :columns="uploadColumns"
              :data-source="fileQueryList"
              :pagination="false"
              :rowKey="
                (record, index) => {
                  return index
                }
              "
              bordered
              size="middle"
              v-show="fileQueryList.length > 0"
            >
              <a
                slot="name"
                slot-scope="text, record"
                @click="previewAttach(record.id, record.fileName)"
                href="javascript:void(0)"
                title="点击预览附件"
                style="color: blue"
                >{{ text }}</a
              >
              <span slot="uploadTime" slot-scope="text">
                {{ timeFormat(text) }}
              </span>
              <span slot="aciton" slot-scope="text, record">
                <span style="color:blue;cursor: pointer;" @click="deletefj(record.id)" type="primary" v-if="record.uploader == currentUserId">删除</span>
                <span style="color:blue;cursor: pointer; margin-left:5px;" @click="doDownLoadBatch(record.id)" type="primary">下载</span>
              </span>
            </a-table>
          </div>

        <a-divider style="margin: 20px 0;" />

          <div>
            <div class="info-title">子任务单明细
              <a-button type="primary" v-show="showEditBtn" @click="kpiAdd()">新增</a-button>
              <a-button type="primary" v-show="showEditBtn" @click="openImportWin()">导入</a-button>
              <a-button style="margin-left: 15px" v-show="showEditBtn" @click="kpiDel()">删除</a-button>
            </div>
            <a-table
              class="hte-table-content"
              :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps: getCheckboxProps }"
              :columns="kpi.columns"
              :data-source="kpi.data"
              bordered
              size="middle"
              :rowKey="
                (record, index) => {
                  return index
                }
              "
              :pagination="false"
              :loading="tableLoading"
            >
              <template slot="taskContent" slot-scope="text, record, index">
                <a-button v-if="form.taskType==61 && !!record.linkId" type="link" @click="goPolicyLink(record.linkId)">{{record.taskContent}}</a-button>
                <a-textarea v-else  v-model="record.taskContent" placeholder="请输入任务内容，500字以内" :auto-size="{ minRows: 1, maxRows: 7 }" :maxLength="500" 
                 @change="checkValueLen(record.taskContent, 500, index, 'taskContent')" :readOnly="(record.detailStatus == '2' || !(record.handleUserId == currentUserId || form.createUserId === currentUserId ) && record.id &&form.id) ? true : false"/>
              </template>
              <template slot="startDate" slot-scope="text, record">
                <a-date-picker v-model="record.startDate" placeholder="请输入任务开始时间" :allowClear="false" :disabled-date="disabledStartDate"  
                      @change="((date,dateString)=>{timeSelect(date,dateString,record,1)})" :disabled="(record.detailStatus == '2' || !(record.handleUserId == currentUserId || form.createUserId === currentUserId ) && record.id &&form.id)? true : false"/>
              </template>
              <template slot="endDate" slot-scope="text, record">
                <a-date-picker v-model="record.endDate" placeholder="请输入任务完成时间" :allowClear="false" :disabled-date="disabledStartDate" 
                      @change="((date,dateString)=>{timeSelect(date,dateString,record,2)})" :disabled="(record.detailStatus == '2' || !(record.handleUserId == currentUserId || form.createUserId === currentUserId ) && record.id &&form.id)? true : false"/>
              </template>
              
              <template slot="handleUserName" slot-scope="text, record">
                <span v-if="form.taskBuildType =='1'">{{ record.handleUserName }}</span>
                <a-select v-if="form.taskBuildType !='1'"
                  show-search
                  :value="record.handleUserName"
                  placeholder="输入账号或者名称查找用户"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchUser"
                  @change="((value,option)=>{handleSubChange(value,option,record)})"
                  :disabled="(record.detailStatus == '2' || !(record.handleUserId == currentUserId || form.createUserId === currentUserId ) && record.id &&form.id)? true : false"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </template>

              <template slot="action" slot-scope="text, record">
                <span v-if="record.id" style="color:blue;" @click="applyData(record)">发起数据申请</span><br>
                <span v-if="record.id" style="color:blue;" @click="openProcessDetail(record)">数据流程</span>
              </template>
              <template slot="personalAttach" slot-scope="text, record">
                <a-button type="default" @click="toFile(record)" v-if="record.id" :disabled=" !(record.handleUserId == currentUserId || form.createUserId == currentUserId) ? true : false">附件&nbsp;<span style="size:10px;color:rgb(255, 116, 93);">({{record.fileAmount}})</span></a-button>
              </template>
              
            </a-table>
          </div>
        </a-form-model>
        <div class="btn-box">
          <a-button v-show="showEditBtn" style="margin-right: 15px" @click="doSubmit(false)">保存</a-button>
          <a-button style="margin-right: 15px" type="primary" @click="doSubmit(true)" v-show="form.id != '' && form.status == '1' && form.createUserId === currentUserId">确认任务单</a-button>
          <a-button style="margin-right: 15px" type="primary" @click="finishTask()" v-show="showFinishBtn">完成任务单</a-button>
          <a-button style="margin-right: 15px" @click="sendTask" v-show="form.id != '' && form.status != '1' && form.createUserId === currentUserId">发送娅米消息通知</a-button>
        </div>
      </div>
    </div>
    
    <a-modal
      v-model="visibleModelHistory"
      width="70vw"
      :bodyStyle="{ padding: '10px', backgroundColor: '#f4f5fa' }"
      title="变更历史"
      :footer="null"
      :key="id"
    >
      <task-change-history :hid="id"></task-change-history>
    </a-modal>

    <a-modal
      v-model="visibleModelProcess"
      width="70vw"
      :bodyStyle="{ padding: '10px', backgroundColor: '#f4f5fa' }"
      title="流程状态"
      :footer="null"
      :key="processId"
    >
      <task-tech-process :detailId="processId"></task-tech-process>
    </a-modal>

    <a-modal class="selectedPerson" title="附件信息" :visible="attachVisible" width="80vw" @cancel="handleAttachClose()" :footer="null" :destroyOnClose="true" :key="'attach'+busKey">
      <attach-tab :bus-field="busField" :bus-key="busKey" :bus-type="busType" @closeAttachModal="handleAttachClose()"></attach-tab>
    </a-modal>
    <!--导入子节点-->
    <excel-paste
      :columnsExcel="columnsExcel"
      :exportXlsTemplateUrl="exportXlsTemplateUrl"
      :exportXlsTemplateRequestUrl="exportXlsTemplateRequestUrl"
      :excelVisible="excelVisible"
      :excelConfirmLoading="excelConfirmLoading"
      @handleOkExcel="handleOkExcel"
      @handleCancelExcel="handleCancelExcel"
    ></excel-paste>
  </div>
</template>

<script>
import { getAction, postAction,previewAttach } from '@/api/manage'
import moment from 'moment';
import '@/config/upload.install.js'
import Vue from 'vue'
import { Modal } from 'ant-design-vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { getParamValFromUrl, formatFileSize, endWith } from '@/utils/common.js'
import { simpleDebounce } from '@/utils/util'
import ExcelPaste from '@/components/excelPaste/ExcelPaste'

const uploadColumns = [
  {
    title: '附件名称',
    dataIndex: 'fileName',
    scopedSlots: { customRender: 'name' },
 
  },
  {
    title: '上传人',
    dataIndex: 'uploaderName',
    width: '10%'
  },
  {
    title: '上传时间',
    dataIndex: 'uploadTime',
    align: 'center',
    width: '15%',
    scopedSlots: { customRender: 'uploadTime' },
  },
  {
    title: '操作',
    dataIndex: 'aciton',
    align: 'center',
    scopedSlots: { customRender: 'aciton' },
    width: '10%'
  },
]

export default {
  components: {
    ExcelPaste,
    HomeNav: () => import('@/components/layouts/HomeNav'),
    TaskChangeHistory: () => import('@views/myTask/TaskChangeHistory'),
    TaskTechProcess: () => import('@views/myTask/TaskTechProcess'),
    AttachTab: () => import('@/views/projectBuildTask/AttachTab')
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'dailyTaskAdd',
      },
      uploadColumns,
      selectedRowKeys: [],
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      tableSelectKey: '',
      showEditBtn:true,
      showFinishBtn:false,
      form: {
        id: '',
        taskType: '',
        taskTypeName: '',
        taskBuildType: '',
        taskName: '',
        createDate:'',
        startDate: '',
        endDate: '',
        createUserName: '',
        mainDeptId:'',
        mainDeptName:'',
        target:'',
        saveFlag: false,
        status: '',
        taskNo: '',
        versionNo: '',
        handlerId: '',
        handlerName: undefined,
        hasSendNotice: '1',
        openRange:'',
        openRangeName:'',
        productSystem:'',
        productSystemName:'',
        doctorId:'',
        doctorName: undefined,
        workDeptId:'',
        workDeptName: undefined,
        teacherId:'',
        teacherName: undefined,
        reseachTopic:'',
        station:'',
        stationTeacher:'',
        amount:'',
        manageType:'',
        manageError:'',
        managePoint:'',
      },
      rules: {
        taskName: [
          { required: true, message: '请输入任务单名称', trigger: 'blur' },
          { min: 1, max: 50, message: '任务单名称不超过50个字符', trigger: 'blur' },
        ],
        versionNo: [
          { required: true, message: '请输入版本号', trigger: 'blur' },
          { pattern: /[vV]\d{1,2}\.\d{1,2}\.\d{1,2}$/, message: '格式v1.0.0 || V1.0.0 ', trigger: 'blur' },
        ],
        target: [
          { required: true, message: '请输入任务单完成目标', trigger: 'blur' },
          { min: 1, max: 500, message: '任务单完成目标不超过500个字符', trigger: 'blur' },
        ],
        taskBuildType: [{ required: true, message: '请选择任务单类型', trigger: 'blur' }],
        startDate: [{ required: true, message: '请选择任务开始时间', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择任务完成时间', trigger: 'change' }],
        productSystem: [{ required: true, message: '请选择产品系统', trigger: 'change' }],
        handlerName: [{ required: true, message: '请输入迭代负责人', trigger: 'blur' }],
        doctorName: [{ required: true, message: '请输入博士后姓名', trigger: 'blur' }],
        workDeptName: [{ required: true, message: '请输入工作部门/经营体', trigger: 'blur' }],
        teacherName: [{ required: true, message: '请输入工作站导师', trigger: 'blur' }],
        reseachTopic: [{ required: true, message: '请输入研究项目课题', trigger: 'blur' }],
        station: [{ required: true, message: '请输入流动站名称', trigger: 'blur' }],
        stationTeacher: [{ required: true, message: '请输入流动站导师', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入联合培养费', trigger: 'blur' }],
      },
      url: {
        save: '/projectWorkTask/save',
        getAttachInfo: '/tp/attach/getAttaches',
        getWorkTask: '/projectWorkTask/queryById',
        sendTask: '/projectWorkTask/sendTask',
        codeInfoList: '/manage/codeInfo/list',
        getUserList: '/lib/hteFileClass/getUserListOnlyUpms',
        getDeptList: '/lib/hteFileClass/getDeptList',
        downLoadBatch: '/common/downLoadBatch',
        deleteBatch: '/tp/attach/delete',
        getVersionTopFive: '/projectWorkTask/getVersionTopFive',
        addSubTaskBatch:'/projectWorkTask/addSubTaskBatch',
      },
      kpi: {
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 50,
            customRender: (text,record,index) => `${index+1}`,
          },
          {
            title: '子任务单内容',
            dataIndex: 'taskContent',
            scopedSlots: { customRender: 'taskContent' },
          },
          {
            title: '子任务开始时间',
            dataIndex: 'startDate',
            width: '15%',
            scopedSlots: { customRender: 'startDate' },
            sorter: (a, b) => a.startDate.localeCompare(b.startDate)
          },
          {
            title: '子任务完成时间',
            dataIndex: 'endDate',
            width: '15%',
            scopedSlots: { customRender: 'endDate' },
            sorter: (a, b) => a.endDate.localeCompare(b.endDate)
          },
          {
            title: '具体执行人员',
            dataIndex: 'handleUserName',
            scopedSlots: { customRender: 'handleUserName' },
            width: '15%'
          },
          {
            title: '个人附件',
            dataIndex: 'personalAttach',
            scopedSlots: { customRender: 'personalAttach' },
            width: '100px'
          },
        ],
        data: [],
        selRowIds: [],
      },
      fileList: [],
      fileQueryList: [],
      id:'',
      addFlag:false,
      nowDate: moment().format('YYYY-MM-DD'),
      currentUserId:'',
      productSystemOptions:[],
      fetching:false,
      userData:[],
      userOpenData:[],
      userHandleData:[],
      userDoctorData:[],
      workDeptData:[],
      userTeacherData:[],
      outOpenRangeName:undefined,
      versionTip:'',
      casProductSystemOptions:[],
      casModel:[],
      visibleModelHistory:false,
      processId:0,
      visibleModelProcess:false,
      columnsAddFlag:false,
      attachVisible:false,
      busField: 'dailyTaskAttach',
      busKey: '',
      busType: 'dailyTaskAttach',
      tableLoading:false,
      quarterList:[
        {label: '第一季度', code: 1},{label: '第二季度', code: 2},{label: '第三季度', code: 3},{label: '第四季度', code: 4},
      ],
      yearList:[],
      excelVisible: false,
      columnsExcel: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
          isImportExcelColumns: false,
        },
        {
          title: '子任务单内容',
          dataIndex: 'taskContent',
        },
        {
          title: '子任务开始时间',
          dataIndex: 'startDate',
          width: '15%',
        },
        {
          title: '子任务完成时间',
          dataIndex: 'endDate',
          width: '15%',
        }
      ],
      excelHandleUserCol:{
        title: '具体执行人员',
        dataIndex: 'handleUserId',
        width: '15%'
      },
      excelConfirmLoading: false,
      excelDataSource: [],
      exportXlsTemplateUrl: 'templates/excel/subTaskListImport.xls',
      exportXlsTemplateRequestUrl: '/common/exportXlsTemplate',
    }
  },
  created () {
    const obj = this.$route.query
    this.id = obj.id;
    if (this.id) {
      this.initData(this.id)
    } else {
      this.form.mainDeptId = Vue.ls.get(USER_INFO).deptId
      this.form.mainDeptName = Vue.ls.get(USER_INFO).deptName
      this.form.createUserName = Vue.ls.get(USER_INFO).realname
      this.form.taskType = obj.projectClass;
      this.form.taskTypeName = obj.projectName;
      this.addFlag = true;
      if (this.form.taskType == 30 || this.form.taskType == 'hrManage') {
        this.form.taskBuildType = '2'
      }
      this.initSelectData();
    }
    this.currentUserId = Vue.ls.get(USER_INFO).username
  },
  methods: {
    casLoadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      let arr = []
      this.productSystemOptions.map((item) => {
        if (item.title == targetOption.title) {
          arr.push({ value: item.value, label: item.label,title: item.label})
        }
      })
      targetOption.children = arr
      targetOption.loading = false;
      this.casProductSystemOptions = [...this.casProductSystemOptions];
    },
    casProductSystemOnChange(value,selectedOptions) {
      this.form.productSystem = selectedOptions && selectedOptions[1] ? selectedOptions[1].value: ''
      this.form.productSystemName = selectedOptions && selectedOptions[1] ? selectedOptions[1].label: ''
      this.$set(this.form,'productSystem',selectedOptions && selectedOptions[1] ? selectedOptions[1].value: '');
      this.$set(this.form,'productSystemName',selectedOptions && selectedOptions[1] ? selectedOptions[1].label: '');
      if (this.form.productSystem) {
        this.getVersionTopFive( this.form.productSystem)
      }
    },
    fetchHandleUser(val) {
      if (val) {
        this.userHandleData = [];
        this.fetching = true;
        getAction(this.url.getUserList, { name: val }).then(res => {
          if (res.success) {
            this.userHandleData = res.result;
            this.fetching = false;
          }
        });
      }
    },
    // 迭代负责人
    fetchHandleChange(value,option) {
      this.$set(this.form,'handlerId',value);
      let text = option.componentOptions.children[0].text.trim();
      let realText = text ? text.split("(")[0] : "";
      this.$set(this.form,'handlerName',realText);
    },
    fetchDoctorUser(val) {
      if (val) {
        this.userDoctorData = [];
        this.fetching = true;
        getAction(this.url.getUserList, { name: val }).then(res => {
          if (res.success) {
            this.userDoctorData = res.result;
            this.fetching = false;
          }
        });
      }
    },
    // 博士后姓名
    fetchDoctorChange(value,option) {
      this.$set(this.form,'doctorId',value);
      let text = option.componentOptions.children[0].text.trim();
      let realText = text ? text.split("(")[0] : "";
      this.$set(this.form,'doctorName',realText);
    },
    fetchTeacherUser(val) {
      if (val) {
        this.userTeacherData = [];
        this.fetching = true;
        getAction(this.url.getUserList, { name: val }).then(res => {
          if (res.success) {
            this.userTeacherData = res.result;
            this.fetching = false;
          }
        });
      }
    },
    // 工作站导师
    fetchTeacherChange(value,option) {
      this.$set(this.form,'teacherId',value);
      let text = option.componentOptions.children[0].text.trim();
      let realText = text ? text.split("(")[0] : "";
      this.$set(this.form,'teacherName',realText);
    },
    fetchWorkDept(val) {
      if (val) {
        this.workDeptData = [];
        this.fetching = true;
        getAction(this.url.getDeptList, { name: val }).then(res => {
          if (res.success) {
            this.workDeptData = res.result;
            this.fetching = false;
          }
        });
      }
    },
    // 工作部门/经营体
    workDeptChange(value,option) {
      this.$set(this.form,'workDeptId',value);
      this.$set(this.form,'workDeptName',option.componentOptions.children[0].text.trim());
    },
    fetchOpenUser(val) {
      if (val) {
        this.userOpenData = [];
        this.fetching = true;
        getAction(this.url.getUserList, { name: val }).then(res => {
          if (res.success) {
            this.userOpenData = res.result;
            this.fetching = false;
          }
        });
      }
    },
    // 开放范围
    handleOpenChange(value,option) {
      this.$set(this.form,'openRange',value.join(","));
      let arr = []
      option.forEach(item=> {
        let text = item.componentOptions.children[0].text?item.componentOptions.children[0].text.trim():''
        let realText = text ? text.split("(")[0] : "";
        arr.push(realText)
      })
      this.$set(this.form,'openRangeName',arr.join(','));
    },
    loadRange(nameList) {
      if (nameList) {
        this.userOpenData = [];
        this.fetching = true;
        getAction(this.url.getUserList, { nameList: nameList }).then(res => {
          if (res.success) {
            this.userOpenData = res.result;
            this.fetching = false;
          }
        });
      }
    },
    fetchUser(val) {
      if (val) {
        this.userData = [];
        this.fetching = true;
        getAction(this.url.getUserList, { name: val }).then(res => {
          if (res.success) {
            this.userData = res.result;
            this.fetching = false;
          }
        });
      }
    },
    // 明细处理人
    handleSubChange(value,option,record) {
      let index = this.kpi.data.findIndex(item=>item.key === record.key)
      if (index != -1) {
        this.kpi.data[index].handleUserId = value
        let text = option.componentOptions.children[0].text.trim();
        let realText = text ? text.split("(")[0] : "";
        this.kpi.data[index].handleUserName = realText
      }
    },
    initSelectData() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '产品系统', isdel: 0,pageSize:-1})
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            let uniqueArr = []
            let parentid = ''
            this.productSystemOptions =[]
            this.casProductSystemOptions =[]
            if (list != null) {
              list.records.map((item) => {
                vm.productSystemOptions.push({ value: item.code, label: item.name,title: item.parentid })
                if (uniqueArr.indexOf(item.parentid) == -1) {
                  uniqueArr.push(item.parentid)
                  vm.casProductSystemOptions.push({ value: item.parentid, label: item.parentid,isLeaf:false,title: item.parentid})
                }
                if (item.code == this.form.productSystem) {
                  parentid = item.parentid
                }
              })
              if (this.form.productSystem) {
                this.casProductSystemOptions.map((item) => {
                  let arr = []
                  vm.productSystemOptions.map((subItem) => {
                    if (subItem.title == item.value) {
                      arr.push({ value: subItem.value, label: subItem.label,title: subItem.label})
                    }
                  })
                  item.children = arr
                })
                this.casProductSystemOptions = [...this.casProductSystemOptions];
                this.casModel = []
                this.casModel.unshift(parentid)
                this.casModel.push(this.form.productSystem)
              }
            }
          } else {
            this.$message.warning('查询产品系统失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询产品系统失败:' + res.message)
        })
      // 奖励申请任务单，设置当前年份
      if(this.form.taskType=='12'){
        const year = String(new Date().getFullYear())
        const lastNum = year.slice(year.length-1,year.length)
        let yearList = []
        for(var i = lastNum; i >= 0; i--){
          yearList.push({label: `202${i}年`,code: parseInt(`202${i}`)})
        }
        this.yearList=yearList;
      }
    },
    getVersionTopFive(value){
      var vm = this
      getAction(this.url.getVersionTopFive, { type: value})
        .then((res) => {
          if (res.code == 200 &&  res.result) {
            vm.versionTip = res.result.join(",")
          }
        })
    },
    // 实时校验长度
    checkValueLen: simpleDebounce(function(val, len, index, key) {
      if(!val) return
      const leng = val.length
      const obj = this.kpi.data[index]
      if (leng > len) {
        obj[key] = val.slice(0, len)
        this.$set(this.kpi.data, index, obj)
        this.$message.warning(`输入内容超出${len}长度，将自动进行截取`)
      }
    }, 500),
    timeFormat(time) {
      if (time) {
        return moment(time).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    disabledDate(current) {
      if (this.form.taskType == '11') {
        return
      }
       return current < moment().subtract(31, 'days').endOf('day');
    }, 
    disabledEndDate(current) {
       return current <  moment(this.form.startDate).subtract(1, 'days').endOf('day');
    },
    disabledStartDate(current) {
      //  || current.isoWeekday() == 6 || current.isoWeekday() == 7
       return current <  moment(this.form.startDate).subtract(1, 'days').endOf('day') ||  current > moment(this.form.endDate).endOf('day') ;
    },
    timeSelect(date,dateString,record,id) {
      let startDateStr = record.startDate ? moment(record.startDate).format('YYYY-MM-DD') : record.startDate;
      let endDateStr = record.endDate ? moment(record.endDate).format('YYYY-MM-DD') : record.endDate;
      let formStartDateStr = this.form.startDate;
      let formEndDateStr = this.form.endDate;   
      if (!formStartDateStr || !formEndDateStr) {
        this.$message.warning('请先填写单头的开始时间和结束时间');
        if (id === 1) {
            this.kpi.data.forEach(item => {
              // bugger todo 
              if (item.key === record.key) {
                item.startDate = ''
              }
            })
          } else {
            this.kpi.data.forEach(item => {
              if (item.key === record.key) {
                item.endDate = ''
              }
            })
          }
        return;
      }
      
      if(startDateStr&&startDateStr!=''&&endDateStr&&endDateStr!=''){
        if(moment(startDateStr).diff(moment(endDateStr),'days') > 0 ){
          this.$message.warning('开始时间不能大于完成时间');
          if (id === 1) {
            this.kpi.data.forEach(item => {
              if (item.key === record.key) {
                item.startDate = ''
              }
            })
          } else {
            this.kpi.data.forEach(item => {
              if (item.key === record.key) {
                item.endDate = ''
              }
            })
          }
          return;
        }
        
        // if (this.form.taskType == '30') {
        //   //完成时间不能大于开始时间3天
        //   let momStartDate = moment(startDateStr);
        //   let momEndDate = moment(endDateStr);
        //   let days =  momEndDate.diff(momStartDate,'days') + 1;
        //   if (days > 3) {
        //     while ((momEndDate.diff(momStartDate,'days') + 1) != 0) {
        //       if (momStartDate.isoWeekday() == 6 || momStartDate.isoWeekday() == 7) {
        //         days -=1;
        //       }
        //       momStartDate.add(1,'days')
        //     }
        //   }
        //   if (days > 3) {
        //     this.$message.warning('完成时间不能大于开始时间3天');
        //     if (id === 1) {
        //       this.kpi.data.forEach(item => {
        //       if (item.key === record.key) {
        //           item.startDate = ''
        //         }
        //       })
        //     } else {
        //       this.kpi.data.forEach(item => {
        //       if (item.key === record.key) {
        //           item.endDate = ''
        //         }
        //       })
        //     }
        //     return;
        //   }
        // }
      }
      if (id === 1) {
        if (!startDateStr) {
          this.$message.warning('请填写子任务单开始时间');
          this.kpi.data.forEach(item => {
              if (item.key === record.key) {
                item.startDate = ''
              }
            })
          return
        }
        if (moment(startDateStr).diff(moment(formEndDateStr),'days') > 0) {
            this.$message.warning('子任务单开始时间不允许大于单头结束时间');
            this.kpi.data.forEach(item => {
              if (item.key === record.key) {
                item.startDate = ''
              }
            })
            return;
        }
        this.kpi.data.forEach(item => {
          if (item.key === record.key) {
            item.startDate = dateString
          }
        })
      } else {
        if (!endDateStr) {
          this.$message.warning('请填写子任务单结束时间');
          this.kpi.data.forEach(item => {
              if (item.key === record.key) {
                item.endDate = ''
              }
            })
          return
        }
        if (moment(endDateStr).diff(moment(formEndDateStr),'days') > 0) {
            this.$message.warning('子任务单结束时间不允许大于单头结束时间');
            this.kpi.data.forEach(item => {
              if (item.key === record.key) {
                item.endDate = ''
              }
            })
            return;
        }

        this.kpi.data.forEach(item => {
          if (item.key === record.key) {
            item.endDate = dateString
          }
        })
      }
    },
    dateSelect(date,dateString,id) {
      let startDateStr = this.form.startDate;
      let endDateStr = this.form.endDate;
      if(startDateStr&&startDateStr!=''&&endDateStr&&endDateStr!=''){
        if(moment(startDateStr).diff(moment(endDateStr),'days') > 0){
          this.$message.warning('开始时间不能大于完成时间');
          if (id === 1) {
            this.form.startDate = ''
          } else {
            this.form.endDate = ''
          }
          return;
        } 
        // if(endDateStr.diff(moment(startDateStr),'days') > 3){
        //   this.$message.warning('完成时间不能大于开始时间3天');
        //   if (id === 1) {
        //     this.form.startDate = ''
        //   } else {
        //     this.form.endDate = ''
        //   }
        //   return;
        // }
      }
      if (id===1) {
        this.form.startDate = dateString
      } else {
        this.form.endDate = dateString
      }
    },
    kpiAdd() {
      if (!this.form.taskBuildType) {
        this.$message.warning('请先选择任务单类型')
        return;
      }
      if (!this.form.startDate) {
        this.$message.warning('请先选择任务开始时间')
        return;
      }
      if (!this.form.endDate) {
        this.$message.warning('请先选择计划完成时间')
        return;
      }
      let username = undefined
      let realname = undefined
      if (this.form.taskBuildType === "1"){
        username = Vue.ls.get(USER_INFO).username
        realname = Vue.ls.get(USER_INFO).realname
      }
      this.kpi.data.unshift({
        key: this.kpi.data.length + 1 + new Date().getTime(),
        taskContent: '',
        startDate: '',
        endDate: '',
        handleUserId: username,
        handleUserName: realname,
      })
    },
    openImportWin: function () {
      if(!this.id){
        this.$message.warning('请先保存任务单');
        return;
      }
      if(this.form.taskBuildType=='2'){
        this.columnsExcel.push(this.excelHandleUserCol);
      }
      this.excelVisible = true
    },
    handleOkExcel: function (data) {
      this.excelDataSource = []
      for (let index = 0; index < data.length; index++) {
        const element = data[index]
        if (this.form.taskBuildType=='2'&&
          (element.taskContent === '' ||
          element.startDate === '' ||
          element.endDate === '' ||
          element.handleUserId === '')
        ) {
          this.$message.warning('子任务单内容、子任务开始时间、子任务完成时间、具体执行人员必填')
          return
        }
        if (this.form.taskBuildType=='1'&&
          (element.taskContent === '' ||
            element.startDate === '' ||
            element.endDate === '')
        ) {
          this.$message.warning('子任务单内容、子任务开始时间、子任务完成时间必填')
          return
        }

        let startDate = new Date(element.planStartDate)
        let endDate = new Date(element.completionDate)
        if (startDate > endDate) {
          this.$message.warning(`子任务：[${element.taskContent}] 开始时间不能大于结束时间`)
          return
        }
        //日期格式化
        element.planStartDate = this.formatDate(startDate)
        element.completionDate = this.formatDate(endDate)
        element.parentId = this.id
        if (this.form.taskBuildType=='1'){
          element.handleUserId=this.form.createUserId;
        }
      }
      this.excelDataSource = data
      //数据验证
      this.excelConfirmLoading = true
      postAction(this.url.addSubTaskBatch, this.excelDataSource)
        .then((res) => {
          this.excelConfirmLoading = false
          if (res.code === 200) {
            this.excelVisible = false
            this.$message.success('导入成功')
            this.initData(this.id);
          } else {
            this.$message.warning('操作异常:' + res.message)
          }
        })
        .catch((res) => {
          this.excelConfirmLoading = false
          this.$message.warning('操作异常:' + res.message)
        })
    },
    formatDate: function (date) {
      let year = date.getFullYear()
      let month = (Array(2).join('0') + (date.getMonth() + 1)).slice(-2)
      let dateStr = (Array(2).join('0') + date.getDate()).slice(-2)
      return [year, month, dateStr].join('-')
    },
    handleCancelExcel: function () {
      this.excelVisible = false
    },
    kpiDel() {
      if (this.kpi.selRowIds.length == 0) {
        this.$message.warning('请选择要删除的明细记录')
        return
      }

      if (this.kpi.data.length == 1) {
        this.$message.warning('该任务单只有一条子任务，不能删除')
        return
      }
      const that = this;
      Modal.confirm({
        title: '提示',
        content: '删除子任务之前请先保存任务信息，避免数据丢失',
        onOk() {
          const list = that.kpi.selRowIds.map(function (item) {
            return item.id
          })
          that.delAjax(list)
          that.kpi.selRowIds = []
          that.selectedRowKeys = [] 
        },
        onCancel() {},
      })
    },
    delAjax(list) {
        // todo ajax 刷新整个页面 
      postAction('/projectWorkTask/detailBatchDelete', {"list":list,"taskBuildType":2})
      .then((res) => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.initData(this.form.id)
        } else {
          const msg = res.message == null ? res.result : res.message
          this.$message.error(msg)
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    sendTask () {
      const that = this;
      postAction(that.url.sendTask, that.form).then((res) => {
          if (res.code === 200) {
              that.$message.success('发送成功');
          } else {
              const msg = res.message == null ? res.result : res.message;
              that.$message.error(msg);
          }
      }).catch(err=>{
          console.log(err)
      })
    },
    doSubmit(saveFlag) {
      this.$refs.ruleForm.validate((err, values) => {
        if (!err) {
          this.$message.error('请填写完整任务单头信息');
          return;
        } 
        
        let flag = false;
        let timeFlag = false;
        // if (this.kpi.data.length === 0 && this.form.taskBuildType != '1') {
        //   this.$message.error('子任务明细没填写完整');
        //   return;
        // }

        if (this.kpi.data.length > 0) {
          this.kpi.data.forEach(item=> {
            if (item.taskContent === '' || item.startDate ==='' || item.endDate==='' || item.handleUserName==='' || item.handleUserId==='' || !item.handleUserId) {
                flag = true;
            } else {
              if (moment(item.startDate).diff(moment(this.form.startDate),'days') < 0 || moment(item.startDate).diff(moment(this.form.endDate),'days') > 0) {
                timeFlag = true;
              }
              if (moment(item.endDate).diff(moment(this.form.startDate),'days') < 0 || moment(item.endDate).diff(moment(this.form.endDate),'days') > 0) {
                timeFlag = true;
              }
            }
          })
        }

        if (timeFlag) {
          this.$message.error('子任务单的时间不在任务单头时间范围内');
          return;
        }
        
        if (flag) {
          this.$message.error('子任务明细没填写完整');
          return;
        }

        this.form.detail = this.kpi.data
        if (this.form.status && this.form.status != '1') {
          saveFlag = true
        }
        this.form.saveFlag = saveFlag
        const that = this;
        postAction(that.url.save, that.form).then((res) => {
            if (res.code === 200) {
              if (!this.form.status) {
                that.$message.success('创建任务单成功，需要点击确认任务单才会生效',5);
              } else {
                 that.$message.success('保存成功');
              }
                that.form.id = res.result
                that.initData(that.form.id);
                if (that.addFlag) {
                  that.bindBusKey();
                  that.$router.push({path:'/dailyTaskAdd',query:{id: res.result}})
                }
            } else {
                const msg = res.message == null ? res.result : res.message;
                that.$message.error(msg);
            }
        }).catch(err=>{
            console.log(err)
        })
      })
    },
    finishTask(){
      const that = this
      this.$confirm({
        title: '请确认子任务是否都已报工完成，确定完成任务单？',
        onOk() {
          that.form.status=2;
          that.doSubmit(true)
        },
        onCancel() {},
      })
    },
    initData(id) {
      getAction(this.url.getWorkTask, {id: id}).then((res) => {
        if (res.code === 200) {
            this.form = res.result
            // drcary
            if (this.form.openRange) {
              this.outOpenRangeName = this.form.openRange.split(',')
              this.loadRange(this.form.openRange)
            }
            
            if (this.form.taskType == '10' && !this.columnsAddFlag) {
              this.kpi.columns.splice(0,1,{
                title: '编号',
                dataIndex: 'id',
                key: 'id',
                align: 'center',
                width: '8%',
              })
              
              this.kpi.columns.push({
                title: '操作',
                dataIndex: 'action',
                key: 'action',
                align: 'center',
                width: '10%',
                scopedSlots: { customRender: 'action' },
              })
              this.columnsAddFlag = true
            }
            this.kpi.data = res.result.detail
            this.kpi.data.forEach((item,index) =>{
              item.key = index+1
            })
            this.initSelectData();
            this.freshFileAmounts()
            this.id = this.form.id
            this.loadAttachInfo()
          this.showFinishBtn=this.form.taskType == '12'&&this.form.id != '' && this.form.status == '3' && this.form.createUserId === this.currentUserId;
          if(this.form.taskType == '12'&&this.form.status == '2'){
            this.showEditBtn=false;
          }
        } else {
            //const msg = res.message == null ? res.data : res.message;
            this.$message.error(res.message);
        }
      })
    },
    loadAttachInfo() {
      getAction(this.url.getAttachInfo, {
        dbKey: 'Trd',
        busKey: this.id,
        busField: 'workTask',
        busType: 'workTask',
        ftpKey: 'ftp',
      }).then((res) => {
        this.fileQueryList = res.data || []
      })
    },
    previewAttach(attachId, fileName) {
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        this.doDownLoadBatch(attachId)
        return
      }

      let params={
        id:attachId,
        ftpKey:'ftp'
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
        window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        let downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      let iframe = document.getElementById('_attachToolView_downloadfile_frame')
      iframe.src =
        this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)
    },
    // 绑busKey
    bindBusKey() {
      if (this.fileList.length > 0) {
        const ids = this.fileList.map(function (item) {
          return item.id
        })
        const jsona = { dbKey: 'Trd', id: ids.toString(), busKey: this.form.id }
        var jsonStr = JSON.stringify(jsona)
        this.$refs.myUpload.bindBusKey(jsonStr)
      }
    },
    deletefj(id) {
      const that = this
      this.$confirm({
        title: '是否确认删除？',
        onOk() {
          postAction(that.url.deleteBatch, { id: id,busField: 'workTask', busType: 'workTask', ftpKey: 'ftp'})
          .then((res) => {
            if (res.code == 1) {
              that.$message.success('删除成功')
              that.fileQueryList.splice(
                that.fileQueryList.findIndex((item) => item.id === id),
                1
              )
              that.fileList.splice(
                that.fileList.findIndex((item) => item.id === id),
                1
              )
            } else {
              that.$message.warning('删除失败:' + res.msg)
            }
          })
          .catch((res) => {
            that.$message.warning('删除失败:' + res.msg)
          })
        },
        onCancel() {},
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.kpi.selRowIds = selectedRows
      this.selectedRowKeys = selectedRowKeys
    },
    getCheckboxProps(record) {
      return ({
        props: {
          disabled: (record.detailStatus == '2' || !(record.handleUserId == this.currentUserId || this.form.createUserId === this.currentUserId ) && record.id && this.form.id)? true : false
        }
      })
    },
    openHistory() {
      this.visibleModelHistory = true
    },
    applyData (record) {
      var _input = document.createElement("input");   // 直接构建input
      _input.value = record.id;  // 设置内容
      document.body.appendChild(_input);    // 添加临时实例
      _input.select();   // 选择实例内容
      document.execCommand('copy', false, null)   // 执行复制
      document.body.removeChild(_input); // 删除临时实例
      this.$message.success(`【 ${record.id} 】已经复制到剪切板`)
      window.openLinkByType(
        JSON.stringify({
          url: `http://10.254.2.37:8383/portal/portalpage/index.jsp?yamitoken=\$YAMITOKEN\$`,
          type: ''
        })
      );
    },
    openProcessDetail (record) {
      this.visibleModelProcess = true
      this.processId = record.id+''
    },
    toFile(record){
      this.busKey = record.id+''
      this.attachVisible=true
    },
    handleAttachClose(){
      this.attachVisible=false;
      this.freshFileAmounts()
    },
    freshFileAmounts(){
      if (this.busKey) {
        const index = this.kpi.data.findIndex(item => item.id == this.busKey)
        if (index > -1) {
          this.getAttachNum(this.kpi.data[index],index)
        }
      } else {
        this.kpi.data.forEach((data,index)=>{
          this.getAttachNum(data,index)
        })
      }
    },
    getAttachNum(data,index) {
       getAction(this.url.getAttachInfo,{dbKey:'Trd',busKey:data.id,busField:this.busField,busType:this.busType}).then(res=>{
        if(res.code==1 && res.data!=null){
          data.fileAmount = res.data.length
          this.$set(this.kpi.data, index, data)
        }
      }) 
    },
    goPolicyLink(fileId){
      let urlJump = this.$router.resolve({ path: '/library/file/view/2/' + fileId + '/0' })
      window.open(urlJump.href, '_blank')
    }
  },
  watch: {
    fileList: function (newQuestion, oldQuestion) {
      // this.bindBusKey()
      newQuestion.forEach((item) => {
        var newIndex = this.fileQueryList.findIndex((item2) => item2.id === item.id)
        if (newIndex == -1) {
          this.fileQueryList.push(item)
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.dailyTask {
  height: 100%;
  font-size: 14px;
  .navigator {
    min-height: 100%;
    padding: 27px 125px 50px;
    background-color: #f5f5f5;
  }
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  margin-top: 20px;
  .btn-box {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }
}
.info-title {
  font-size: 16px;
  font-weight: bold;
  position: relative;
  padding-left: 14px;
  color: #333333;
  margin-bottom: 14px;
  &:before {
    content: '';
    position: absolute;
    display: block;
    height: 70%;
    top: 15%;
    width: 3px;
    left: 0;
    background-color: #47a4fa;
  }
  /deep/ .ant-btn{
    margin-left: 10px;
    height: 30px;
    line-height: 30px;
  }
}
/deep/ .el-upload__input {
  display: none !important;
}
/deep/ .ant-calendar-picker {
  width: 100%;
}
/deep/ .ant-modal-header{
  border-radius: 15px 15px 0 0;
  background-image: linear-gradient(90deg, #15b1ff 0%,#1158c9 100%);
}
/deep/ .ant-modal-content{
  border-radius: 15px;
}
/deep/ .ant-modal-title,/deep/ .ant-modal-footer{
  text-align: center;
}
/deep/ .ant-modal-title{
  color: #fff;
}

/deep/ .upload-demo{display: inline-block;}
@media (max-width: 1080px){
  .dailyTask .navigator{padding: 27px 30px 50px !important}
}
</style>